<template>
  <div class="space-y">
    <h2>我的订单</h2>
    <!-- 搜索框 -->
    <div class="search-bar" style="max-width:520px;">
      <input v-model="restaurantNameKeyword" placeholder="输入餐厅名称搜索订单..." @keyup.enter="searchOrders" class="input" />
      <button @click="searchOrders" class="btn">搜索</button>
      <button v-if="restaurantNameKeyword" @click="clearSearch" class="btn ghost">清空</button>
    </div>
    <div v-if="orders.length===0" class="card" style="padding:16px;">暂无订单</div>
    <div v-else class="space-y">
      <div v-for="o in orders" :key="o.id" class="card" style="padding:12px;">
        <div class="row" style="justify-content:space-between;">
          <div><a :href="'#/order/' + o.id" style="color:#1e90ff;">订单号：<b>{{ o.id }}</b></a></div>
          <div class="price">¥ {{ o.totalAmount }}</div>
        </div>
        <!-- 餐厅名称 -->
        <div class="muted">餐厅：{{ restaurantsMap[o.restaurantId] || '-' }}</div>
        <div class="muted">状态：{{ o.status }}</div>
        <!-- 评价状态 -->
        <div v-if="(o.status === 'completed' || o.status === 'COMPLETED')" class="muted">
          评价状态：
          <span v-if="evaluationsMap[o.id]">
            已评价 (评分: {{ evaluationsMap[o.id].score }}分)
          </span>
          <span v-else>未评价</span>
        </div>
        <div class="muted">下单时间：{{ formatOrderDate(o.orderDate) }}</div>
        <div class="row" style="justify-content:flex-end; margin-top:8px;">
          <a :href="'#/order/' + o.id" class="btn" style="margin-right:8px;">查看详情</a>
          <button v-if="canCancelOrder(o)" @click="cancelOrder(o.id)" class="btn" style="background-color: #ff4757; color: white;">取消订单</button>
          <button v-if="canDeleteOrder(o)" @click="deleteOrder(o.id)" class="btn" style="background-color: #747d8c; color: white; margin-left:8px;">删除订单</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data(){ return { orders: [], originalOrders: [], restaurantsMap: {}, restaurantNameKeyword: '', evaluationsMap: {} } },
  async created(){
    const user = JSON.parse(localStorage.getItem('user')||'null')
    if(!user){ location.hash = '#/login'; return }
    await this.loadOrders(user.id)
  },
  methods: {
    async loadOrders(userId) {
      const res = await fetch(`/api/v1/orders?userId=${userId}`)
      this.originalOrders = await res.json() // 保存原始订单数据
      this.orders = [...this.originalOrders] // 复制到显示订单
      
      // 为每个订单获取餐厅信息
      if (this.orders.length > 0) {
        await this.loadRestaurantsInfo()
        await this.loadEvaluationsInfo()
      }
    },
    
    // 加载所有订单的评价信息
    async loadEvaluationsInfo() {
      // 重置评价信息映射
      this.evaluationsMap = {}
      
      // 为每个已完成的订单获取评价信息
      for (const order of this.orders) {
        // 只有已完成的订单才可能有评价
        if (order.status === 'completed' || order.status === 'COMPLETED') {
          try {
            const res = await fetch(`/api/v1/orders/${order.id}/evaluate`)
            if (res.ok) {
              const evaluation = await res.json()
              this.evaluationsMap[order.id] = evaluation
            } else if (res.status === 404) {
              // 订单尚未评价，这是正常情况
              console.log(`订单${order.id}尚未评价`)
              this.evaluationsMap[order.id] = null
            } else {
              // 其他错误情况
              console.error(`加载订单${order.id}评价信息失败，状态码:`, res.status)
              this.evaluationsMap[order.id] = null
            }
          } catch (error) {
            console.error(`加载订单${order.id}评价信息发生网络错误:`, error)
            this.evaluationsMap[order.id] = null
          }
        } else {
          // 非已完成订单，直接设为null
          this.evaluationsMap[order.id] = null
        }
      }
    },
    
    // 根据餐厅名称搜索订单
    searchOrders() {
      if (!this.restaurantNameKeyword.trim()) {
        this.orders = [...this.originalOrders] // 如果关键词为空，显示所有订单
        return
      }
      
      const keyword = this.restaurantNameKeyword.toLowerCase().trim()
      this.orders = this.originalOrders.filter(order => {
        // 获取订单对应的餐厅名称
        const restaurantName = this.restaurantsMap[order.restaurantId]
        // 如果有餐厅名称且包含关键词，则保留此订单
        return restaurantName && restaurantName.toLowerCase().includes(keyword)
      })
    },
    
    // 清空搜索
    clearSearch() {
      this.restaurantNameKeyword = ''
      this.orders = [...this.originalOrders] // 显示所有订单
    },
    
    // 加载所有订单相关的餐厅信息
    async loadRestaurantsInfo() {
      // 获取所有唯一的餐厅ID
      const restaurantIds = [...new Set(this.orders.map(order => order.restaurantId))]
      
      // 为每个餐厅ID获取餐厅信息
      for (const restaurantId of restaurantIds) {
        if (!restaurantId) continue
        
        try {
          const res = await fetch(`/api/v1/restaurants/${restaurantId}`)
          if (res.ok) {
            const restaurant = await res.json()
            this.restaurantsMap[restaurantId] = restaurant.name
          }
        } catch (error) {
          console.error(`加载餐厅${restaurantId}信息失败:`, error)
        }
      }
    },
    
    canCancelOrder(order) {
      // 只有状态为pending的订单才可能被取消
      if (order.status !== 'pending') {
        return false
      }
      
      // 检查订单是否在一分钟内创建
      const orderDate = new Date(order.orderDate)
      const now = new Date()
      const minutesDiff = (now - orderDate) / (1000 * 60)
      
      return minutesDiff < 1
    },
    
    canDeleteOrder(order) {
      // 允许删除已取消或已完成的订单
      return order.status === 'canceled' || order.status === 'completed' || order.status === 'COMPLETED'
    },
    
    async cancelOrder(orderId) {
      const user = JSON.parse(localStorage.getItem('user')||'null')
      if(!user){ location.hash = '#/login'; return }
      
      try {
        const res = await fetch(`/api/v1/orders/${orderId}/cancel?userId=${user.id}`, {
          method: 'PUT'
        })
        
        if (res.ok) {
          alert('订单已成功取消')
          await this.loadOrders(user.id) // 重新加载订单列表
        } else {
          const errorMsg = await res.text()
          alert(errorMsg || '取消订单失败，请稍后再试')
        }
      } catch (error) {
        alert('网络错误，请稍后再试')
      }
    },
    
    async deleteOrder(orderId) {
      const user = JSON.parse(localStorage.getItem('user')||'null')
      if(!user){ location.hash = '#/login'; return }
      
      // 确认删除
      if (!confirm('确定要删除此订单吗？删除后将无法恢复。')) {
        return
      }
      
      try {
        const res = await fetch(`/api/v1/orders/${orderId}?userId=${user.id}`, {
          method: 'DELETE'
        })
        
        if (res.ok) {
          alert('订单已成功删除')
          await this.loadOrders(user.id) // 重新加载订单列表
        } else {
          const errorMsg = await res.text()
          alert(errorMsg || '删除订单失败，请稍后再试')
        }
      } catch (error) {
        alert('网络错误，请稍后再试')
      }
    },
    
    formatOrderDate(dateString) {
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  }
}
</script>


